package controller

import (
	"encoding/base64"
	"fmt"
	"html/template"
	"net/http"
	"strconv"
	"sync"

	"github.com/gorilla/sessions"
)

var look *sync.Mutex = &sync.Mutex{}
var LikeNumber int64 = 1000

var cookiestore *sessions.CookieStore = sessions.NewCookieStore([]byte("something-very-secret"))

type PageData struct {
	Number int64
}

func Main(w http.ResponseWriter, r *http.Request) {
	// 获取一个名为"gosession"的session指针，如果不存在则创建一个新的session
	session, _ := cookiestore.Get(r, "gosession")
	session.Values["sessionkey"] = "sessionvalue" // 设置session值
	session.Save(r, w)                            // 保存session

	// 读取session值
	v := session.Values["sessionkey"]
	fmt.Println(v)

	t, err := template.ParseFiles("view/main.html")
	if err != nil {
		fmt.Println(err.Error())
		w.Write([]byte("template error"))
		return
	}
	w.Header().Add("Server", "igoer server")

	data := PageData{Number: LikeNumber}
	t.Execute(w, data)
}

func Like(w http.ResponseWriter, r *http.Request) {
	cook, _ := r.Cookie("islike")
	if cook != nil {
		w.Write([]byte(`{"code":1}`))
		return
	}

	cookie := http.Cookie{
		Name:   "islike",
		Value:  base64.StdEncoding.EncodeToString([]byte("true")),
		Path:   "/",
		MaxAge: 86400,
	}
	http.SetCookie(w, &cookie)

	look.Lock()
	LikeNumber += 1
	look.Unlock()

	w.Write([]byte(fmt.Sprintf(`{"code":0,"num":%v}`, LikeNumber)))
}

func SetLike(w http.ResponseWriter, r *http.Request) {
	number := r.FormValue("num")
	i, err := strconv.ParseInt(number, 10, 64)
	if err != nil {
		w.Write([]byte(`{"code":1}`))
		return
	}
	LikeNumber = i
	w.Write([]byte(`{"code":0}`))
}

func Js(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "application/javascript")
	http.ServeFile(w, r, "view/htmlcopyer.js")
}

func Css(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "text/css")
	http.ServeFile(w, r, "view/htmlcopyer.css")
}
